package com.code.productorAndCustomer;

public class DemoSync {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.productGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者A").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.customGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者B").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.productGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"生产者C").start();

        new Thread(()->{
            for(int i = 0; i < 10; i++) {
                try {
                    data.customGood();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"消费者D").start();
    }
}

//数据
class Data{
    private int goods;

    public synchronized void productGood() throws InterruptedException {
        while(goods != 0){
            //有商品，生产者等待
            this.wait();
        }
        goods++;
        System.out.println(Thread.currentThread().getName()+"---生产--"+goods);
        //通知其他线程我生产了
        this.notifyAll();
    }

    public synchronized void customGood() throws InterruptedException {
        while (goods == 0){
            //没有商品消费者等待
            this.wait();
        }
        goods--;
        System.out.println(Thread.currentThread().getName()+"---消费--"+goods);
        //呼叫其他线程，我消费了，该生产了
        this.notifyAll();
    }


}
